<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true">
				<el-form-item>
					<el-input v-model="query.keyword" placeholder="姓名"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getDepts">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="depts" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" label="序号" width="100">
			</el-table-column>
			<el-table-column prop="name" label="部门名称" width="150" sortable>
			</el-table-column>
      <el-table-column prop="manager.username" label="部门管理员" width="250" sortable>
      </el-table-column>
      <el-table-column prop="state" label="部门状态" width="150">
        <template slot-scope="scope">
          <el-tag
              :type="scope.row.state == '0' ? 'success' : scope.row.state == '1' ? 'waring' : 'danger'"
              effect="light"
              disable-transitions>
            {{ scope.row.state == '0' ? "正常" : scope.row.state == '1' ? "禁用" : "弃用" }}
          </el-tag>
        </template>
      </el-table-column>
			<el-table-column prop="parent.name" label="上级部门" width="300" sortable>
			</el-table-column>
			<el-table-column label="操作" width="300">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :current-page="query.pageNum" :page-size="query.pageSize" :total="totals" style="float:right;">
			</el-pagination>
		</el-col>

		<!--新增界面-->
		<el-dialog :title="title" :visible.sync="addFormVisible" :close-on-click-modal="false">
			<el-form :model="dept" label-width="80px" :rules="addFormRules" ref="addForm">
        <el-form-item label="部门编号" prop="sn">
          <el-input v-model="dept.sn" auto-complete="off"></el-input>
        </el-form-item>
				<el-form-item label="部门名称" prop="name">
					<el-input v-model="dept.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="部门状态">
					<el-radio-group v-model="dept.state">
						<el-radio class="radio" :label="0">可用</el-radio>
						<el-radio class="radio" :label="1">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
        <el-form-item label="管理员">
        <el-select v-model="dept.manager" value-key="id" placeholder="请选择">
          <el-option
              v-for="item in emps"
              :key="item.id"
              :label="item.username"
              :value="item">
          </el-option>
        </el-select>
        </el-form-item>
        <el-form-item label="上级部门">
          <el-cascader
              v-model="dept.parent"
              :options="tree"
              :props="{
                checkStrictly: true,
                label: 'name',
                value: 'id'
              }"
              clearable></el-cascader>
        </el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="addFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="addSubmit" :loading="addLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	export default {
		data() {
			return {
        title:'',
        query:{
          pageNum:1,
          pageSize:5,
          keyword:''
        },
        dept:{
          id:null,
          sn:'',
          name:'',
          state:null,
          manager:null,
          parent:null
        },
        depts:[],
        emps:[],
        tree:[],
        totals:0,
				listLoading: false,
				sels: [],//列表选中列
				editLoading: false,
				editFormRules: {
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }
					]
				},
				addFormVisible: false,//新增界面是否显示
				addLoading: false,
				addFormRules: {
					name: [
						{ required: true, message: '请输入部门名称', trigger: 'blur' }
					]
				}
			}
		},
		methods: {
      getTree(){
        this.$http.get("/dept/tree").then((res =>{
          this.tree = res.data.resultObj;
        }))
      },
      getEmps(){
        this.$http.get("/emp").then((res =>{
          this.emps = res.data.resultObj;
        }))
      },
      getDeptList(){
        this.$http.post("/dept",this.query).then((res => {
          this.depts = res.data.resultObj.datas;
          this.totals = res.data.resultObj.totals;
          this.listLoading = false;
        })).catch((res => {
          this.$message({
            message: '系统繁忙',
            type: 'warning'
          });
        }))
      },
			handleCurrentChange(val) {
				this.query.pageNum = val;
				this.getDeptList();
			},
			//获取用户列表
			getDepts() {
        this.query.pageNum = 1;
				this.listLoading = true;
        this.getDeptList();
			},
			//删除
			handleDel: function (index, row) {
				this.$confirm('确认删除该记录吗?', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
			    this.$http.delete("/dept/"+row.id).then((res =>{
            this.listLoading = false;
            if(res.data.success){
              this.getDeptList();
              this.$message({
                message: '删除成功',
                type: 'success'
              });
            }
          })).catch( (res => {

          }))
				}).catch(() => {

				});
			},
			//显示编辑界面
			handleEdit: function (index, row) {
        this.title = "编辑部门";
				this.addFormVisible = true;
				this.dept = Object.assign({}, row);
        //回显上级部门数据封装
        //获取选择的数据的dirpath并且以/分割，存在2个问题，数据类型是字符串，顶级部门会多一个空字符串
        let arr = this.dept.dirPath.split("/");
        //声明新数组存放结果
        let parent = [];
        //循环有问题的数组，解决2个问题
        for (let i = 0; i < arr.length; i++) {
            //排除空字符串
            if(arr[i] !== ''){
              //转换类型并放到结果数组
              parent.push(parseInt(arr[i]))
            }
        }
        //把数组给到双向绑定的对象
        this.dept.parent = parent;
			},
			//显示新增界面
			handleAdd: function () {
				this.addFormVisible = true;
        this.title = "新增部门";
				this.dept = {
          id:null,
          sn:'',
          name:'',
          state:null,
          manager:null,
          parent:null
				};
			},

			//新增
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认提交吗？', '提示', {}).then(() => {
							this.addLoading = true;
              if(this.dept.parent){
                let arr = this.dept.parent;
                this.dept.parent = {id:arr[arr.length-1]};
              }
              this.$http.put("/dept",this.dept).then((res => {
                if(res.data.success){
                  	this.$message({
                  		message: '提交成功',
                  		type: 'success'
                  	});
                  	this.$refs['addForm'].resetFields();
                    this.addFormVisible = false;
                  	this.getDeptList();
                    this.getTree();
                    this.addLoading = false;
                }else{
                  this.$message({
                    message: res.data.message,
                    type: 'error'
                  });
                  this.addLoading = false;
                }
              }))
						});
					}
				});
			},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id).toString();
				this.$confirm('确认删除选中记录吗？', '提示', {
					type: 'warning'
				}).then(() => {
					this.listLoading = true;
					let para = { ids: ids };
					this.$http.patch("/dept",para).then((res =>{
              if(res.data.success){
                this.listLoading = false;
                this.query.pageNum = 1;
                this.getDeptList();
                this.$message({
                  message: '删除成功',
                  type: 'success'
                });
              }
          }))
				}).catch(() => {

				});
			}
		},
		mounted() {
      this.getDeptList();
      this.getEmps();
      this.getTree();
		}
	}

</script>

<style scoped>

</style>